<?php

declare(strict_types=1);
/**
 * This file is part of hyperf-ext/auth.
 *
 * @link     https://github.com/hyperf-ext/auth
 * @contact  eric@zhu.email
 * @license  https://github.com/hyperf-ext/auth/blob/master/LICENSE
 */
namespace App\Core\Rpc;

use App\Exception\HttpResponseException;
use Hyperf\RpcClient\AbstractServiceClient;

class Client extends AbstractServiceClient
{
    /**
     * 定义对应服务提供者的服务名称
     * @var string
     */
    protected $rpcName = '';

    protected function __request(string $method, array $params, ?string $id = null)
    {
        $data = null;
        try {
            if ( ! $this->rpcName) {
                $tA = explode('\\', static::class);
                $this->rpcName = str_replace('Service', 'Rpc', $tA[count($tA) - 1]);
            }
            $_params = [
                'rpcName' => $this->rpcName,
                'method' => $method,
                'param' => $params
            ];

            $data = parent::__request('request', $_params, $id);
            if ( ! empty($data['data']) && isset($data['data']['code']) && $data['data']['code'] != 200) {
                responseError($data['data']['message'], $data['data']['code'] ? $data['data']['code'] : 500 );
            } elseif ( ! empty($data['code']) && $data['code'] < -1000) {
                responseError($data['message']);
            }
        } catch (\Exception $e) {
            if ( ! ($e instanceof HttpResponseException)) {
                responseError('服务器繁忙，请稍后重试', 500);
            }
            responseError($e->getMessage(), 500);
        }

        return $data;
    }
}
